package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录页面拦截
 */

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //将ServletRequest转为HTTPServletRequest
        HttpServletRequest request= (HttpServletRequest) req;

        //首先要给用户登录的机会，直接拦截的话session里面是没有用户信息的，所以有关于用户登录和注册的资源我们是要放行的
        String[] urls = {"login.jsp","/css/","/img/","register.jsp","LoginServlet","RegisterServlet","CheckCodeServlet"};
        //获取当前路径名
        String requestURL = request.getRequestURL().toString();
        for (String url : urls) {
            if (requestURL.contains(url)){
                //要是当前路径包含登录相关的资源就放行
                chain.doFilter(req, resp);
                return;
                //要是不包含，就拦截下来，做下面的判断
            }
        }




        //要是登录了，就可以访问其他资源，没登录来就不能访问
        //根据session中的内容判断是否已经登录
        HttpSession session = request.getSession();
        //我们在用户登录后将用户的信息都封装在了session里面
        Object user = session.getAttribute("user");
        if (user!=null){
            //已经登录，那就放行
            chain.doFilter(req, resp);
        }else{
            //没有登录，那就返回登录页面
            req.setAttribute("login_err","您尚未登录！");
            req.getRequestDispatcher("login.jsp").forward(req,resp);

        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
